const musr = require('./users');
var raw_data = new Array(65536);
var unpacked_data = new Array(65536);

exports.setrawdata = function (data, uid) {
  if (uid < 0 || uid > 65535) {
    return { "success": false, "err": "INVALID_UID" };
  }
  raw_data[uid] = data;
  unpacked_data[uid] = m_unpack(data);
  return { "success": true, "err": "" };
}

exports.getrawdata = function (uid, sID) {
  if (sIDrequired && !musr.checkSessionID(sID)) {
    return { "success": false, "err": "INVALID_SID" };
  }
  if (uid < 0 || uid > 65535) {
    return { "success": false, "err": "INVALID_UID" };
  }
  return { "success": true, "data": raw_data[uid] };
}

function m_unpack(data) {
  var ret = {};
  var arr = data.split(',');
  if (arr.length >= 4) {
    ret['lat'] = Number(arr[0]);
    ret['lat_hemisphere'] = arr[1];
    ret['lng'] = Number(arr[2]);
    ret['lng_hemisphere'] = arr[3];
  }
  if (arr.length >= 7) {
    ret['alt'] = Number(arr[4]);
    ret['pressure'] = Number(arr[6]);
  }
  if (arr.length >= 14) {
    ret['vx'] = Number(arr[8]);
    ret['vy'] = Number(arr[9]);
    ret['vz'] = Number(arr[10]);
    ret['ax'] = Number(arr[11]);
    ret['ay'] = Number(arr[12]);
    ret['az'] = Number(arr[13]);
  }
  if (arr.legnth >= 15) {
    ret['mode'] = arr[14];
  }
  ret['timestamp'] = new Date().getTime();
  return ret;
}

exports.getunpackeddata = function (uid, sID) {
  if (sIDrequired && !musr.checkSessionID(sID)) {
    return { "success": false, "err": "INVALID_SID" };
  }
  if (uid < 0 || uid > 65535) {
    return { "success": false, "err": "INVALID_UID" };
  }
  return { "success": true, "data": unpacked_data[uid] };
}

exports.query = function (uids) {
  let cnt = uids.length;
  let ret = [];
  for (let i = 0; i < cnt; i++) {
    let uid = Number(uids[i]);
    if (uid < 0 || uid > 65535) {
      return { "success": false, "err": `INVALID_UID:${uid}` };
    }
    ret.push(unpacked_data[uid]);
  }
  return { "success": true, "data": ret };
}